@page "{id}"
@model Endatix.Samples.WebApp.Pages.FormModel
@{
    ViewData["Title"] = "Form: " + Model.FormId;
}
@section Head {
        <link rel="stylesheet" type="text/css" href="https://unpkg.com/survey-jquery@1.10.5/defaultV2.min.css" />
}

<div id="formContainer"></div>

@{
    var getDefinitionEndpoint = $"{Model.BaseUrl}/api/forms/{Model.FormId}/definition";
    var submitSubmissionEndpoint = $"{Model.BaseUrl}/api/forms/{Model.FormId}/submissions";
    var isFormDefined = Model.Form.JsonData != null;
}

@section Scripts {
        <script type="text/javascript" src="https://unpkg.com/survey-jquery@1.10.5/survey.jquery.min.js"></script>
        <script type="text/javascript" src="https://unpkg.com/survey-jquery@1.10.5/themes/index.min.js"></script>
        <script>
           $(function() {
                Survey.StylesManager.applyTheme("defaultV2");
                window.formData = "@Model.Form.JsonData";
                if (window.formData.length > 2){
                    try {
                        window.formData = window.formData.replaceAll("&quot;", "\"")
                        var parsedData = JSON.parse(window.formData);
                        window.formData = {
                            jsonData : parsedData
                        };
                    } catch {
                        window.formData = "";
                    }
                }

                 function initializeForm(data) {
                     if (!data?.jsonData) {
                         console.error("Expected jsonData property, but got none. Please check formDefinition endpoint");
                         return;
                     }

                     const form = new Survey.Model(data.jsonData);
                     form.onComplete.add(submitForm);

                     $("#formContainer").Survey({
                         model: form
                     });
                 }

                 function submitForm(sender, options) {
                     const formData = JSON.stringify(sender.data, null, 3);
                     const metadata = {
                         notes: "From Endatix.Samples.WebApp"
                     };
                     const requestBody = {
                         jsonData: formData,
                         isComplete: true,
                         metadata: JSON.stringify(metadata, null, 3)
                     };

                     $.ajax({
                             method: "POST",
                             url: "@submitSubmissionEndpoint",
                             contentType: "application/json",
                             data: JSON.stringify(requestBody)
                         })
                         .done(function(submission) {
                             console.log("Form data submitted successfully:", submission);
                         })
                         .fail(function(jqXHR, textStatus, errorThrown) {
                             console.error("Failed to submit form data:", textStatus, errorThrown);
                         });
                 }

                 function fetchFormDefinition() {
                     $.ajax({
                             method: "GET",
                             url: "@getDefinitionEndpoint"
                         })
                         .done(initializeForm)
                         .fail(function(jqXHR, textStatus, errorThrown) {
                             console.error("Failed to fetch form definition:", textStatus, errorThrown);
                         });
                 }

                 if (typeof window.formData === 'undefined' || !window.formData) {
                     fetchFormDefinition();
                 } else {
                     initializeForm(window.formData);
                 }
             });
        </script>
}